package com.example.waterfall.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

/**
 * @desc : 网络工具类
 */
public class NetworkUtil {

	/**
	 * 返回网络是否可用。需要权限：
	 * <p>
	 * <b> < uses-permission
	 * android:name="android.permission.ACCESS_NETWORK_STATE" /> </b>
	 * </p>
	 * 
	 * @param context
	 * @return 网络可用
	 */
	public static boolean isAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		return info != null && info.isAvailable();
	}

	/**
	 * 返回Wifi是否启用
	 * 
	 * @param c
	 * @return
	 */
	public static boolean isWIFIActivate(Context c) {
		return ((WifiManager) c.getSystemService(Context.WIFI_SERVICE))
				.isWifiEnabled();
	}

	/**
	 * 修改Wifi状态
	 * 
	 * @param c
	 * @param status
	 */
	public static void changeWIFIStatus(Context c, boolean status) {
		((WifiManager) c.getSystemService(Context.WIFI_SERVICE))
				.setWifiEnabled(status);
	}

	/**
	 * 从网上获取内容get方式
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String getStringFromUrl(String url)
			throws ClientProtocolException, IOException {
		HttpGet get = new HttpGet(url);
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(get);
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity, "UTF-8");
	}

	/**
	 * 请求，返回 获取字符串数据，
	 * @param url
	 *            请求地址
	 * @param method
	 *            方式
	 * @param values
	 *            参数
	 * @return 请求响应
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getStringFromUrl(String url, String method,
			HashMap values) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		String str = "请求参数";
		HttpPost post = new HttpPost(url);
		StringEntity strEntity = new StringEntity(str, "UTF-8");
		// entity.setChunked(true);
		post.setEntity(strEntity);
		HttpResponse response = client.execute(post);

		HttpEntity resEntity = response.getEntity();
		return EntityUtils.toString(resEntity, "UTF-8");
	}

	/**
	 * 发送xml数据请求到服务器端，返回输入流
	 * 
	 * @param url
	 *            xml请求数据地址
	 * @param xmlString
	 *            发送的xml数据流
	 * @return null发送失败，否则返回响应内容
	 */
	public static InputStream getStreamFromUrl(String url, String xmlString)
			throws IOException {

		URL Url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
		conn.setReadTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length",
				String.valueOf(xmlString.getBytes().length));
		OutputStream os = conn.getOutputStream();
		os.write(xmlString.getBytes());
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			
			return conn.getInputStream();
		}
		return null;
	}

	/**
	 * 使用get请求以普通方式提交数据
	 * 
	 * @param map
	 *            传递进来的数据，以map的形式进行了封装
	 * @param path
	 *            要求服务器servlet的地址
	 * @return 返回的boolean类型的参数
	 * @throws Exception
	 */
	public static Boolean submitDataByDoGet(Map<String, String> map, String path)
			throws Exception {
		// 拼凑出请求地址
		StringBuilder sb = new StringBuilder(path);
		sb.append("?");
		for (Map.Entry<String, String> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue());
			sb.append("&");
		}
		sb.deleteCharAt(sb.length() - 1);
		String str = sb.toString();
		System.out.println(str);
		URL Url = new URL(str);
		HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
		HttpConn.setRequestMethod("GET");
		HttpConn.setReadTimeout(5000);
		// GET方式的请求不用设置什么DoOutPut()之类的吗？
		if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			return true;
		}
		return false;
	}

	/**
	 * 普通方式的DoPost请求提交数据
	 * 
	 * @param map
	 *            传递进来的数据，以map的形式进行了封装
	 * @param path
	 *            要求服务器servlet的地址
	 * @return 返回的boolean类型的参数
	 * @throws Exception
	 */
	public static Boolean submitDataByDoPost(Map<String, String> map,
			String path) throws Exception {
		// 注意Post地址中是不带参数的，所以newURL的时候要注意不能加上后面的参数
		URL Url = new URL(path);
		// Post方式提交的时候参数和URL是分开提交的，参数形式是这样子的：name=y&age=6
		StringBuilder sb = new StringBuilder();
		// sb.append("?");
		for (Map.Entry<String, String> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue());
			sb.append("&");
		}
		sb.deleteCharAt(sb.length() - 1);
		String str = sb.toString();

		HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
		HttpConn.setRequestMethod("POST");
		HttpConn.setReadTimeout(5000);
		HttpConn.setDoOutput(true);
		HttpConn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		HttpConn.setRequestProperty("Content-Length",
				String.valueOf(str.getBytes().length));
		OutputStream os = HttpConn.getOutputStream();
		os.write(str.getBytes());
		if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			return true;
		}
		return false;
	}

	/**
	 * 以HttpClient的DoGet方式向服务器发送请数据
	 * 
	 * @param map
	 *            传递进来的数据，以map的形式进行了封装
	 * @param path
	 *            要求服务器servlet的地址
	 * @return 返回的boolean类型的参数
	 * @throws Exception
	 */
	public static Boolean submitDataByHttpClientDoGet(Map<String, String> map,
			String path) throws Exception {
		HttpClient hc = new DefaultHttpClient();
		// 请求路径
		StringBuilder sb = new StringBuilder(path);
		sb.append("?");
		for (Map.Entry<String, String> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue());
			sb.append("&");
		}
		sb.deleteCharAt(sb.length() - 1);
		String str = sb.toString();
		System.out.println(str);
		HttpGet request = new HttpGet(sb.toString());

		HttpResponse response = hc.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
			return true;
		}
		return false;
	}

	/**
	 * 以HttpClient的DoPost方式提交数据到服务器<br>
	 * 在遇上HTTPS安全模式或者操作cookie的时候使用HttpClient会方便很多
	 * 
	 * @param map
	 *            传递进来的数据，以map的形式进行了封装
	 * @param path
	 *            要求服务器servlet的地址
	 * @return 返回的boolean类型的参数
	 * @throws Exception
	 */
	public static Boolean submintDataByHttpClientDoPost(
			Map<String, String> map, String path) throws Exception {
		// 1. 获得一个相当于浏览器对象HttpClient，使用这个接口的实现类来创建对象，DefaultHttpClient
		HttpClient hc = new DefaultHttpClient();
		// DoPost方式请求的时候设置请求，关键是路径
		HttpPost request = new HttpPost(path);
		// 2. 为请求设置请求参数，也即是将要上传到web服务器上的参数
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			NameValuePair nameValuePairs = new BasicNameValuePair(
					entry.getKey(), entry.getValue());
			parameters.add(nameValuePairs);
		}
		// 请求实体HttpEntity也是一个接口，我们用它的实现类UrlEncodedFormEntity来创建对象，注意后面一个String类型的参数是用来指定编码的
		HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
		request.setEntity(entity);
		// 3. 执行请求
		HttpResponse response = hc.execute(request);
		// 4. 通过返回码来判断请求成功与否
		if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
			return true;
		}
		return false;
	}
}
